package com.data.basic.chapter04;

import com.data.basic.chapter03.Queue;

/**
 *  链表实现队列
 *  改造原来的链表
 *          1.在head（第一个元素的位置）完成出队，在tail（最后一个元素的位置）端插入元素
 *          2.由于没有dummyHead ,要注意链表为空的情况
 *
 *       {1}→2→3→4→5→6→78→【10】
 *       {}==>表示队列头
 *       【】==> 表示队尾
 * Created by wangbing on 2018/5/3.
 */
public class LinkedListQueue<E>  implements Queue<E>{
    private Node head,tail;
    private int size;



    public LinkedListQueue() {
        this.head=null;
        this.tail=null;
        this.size=0;
    }

    private class Node{
        private E e;
        private Node next;

        public Node(E e,Node next) {
            this.e = e;
            this.next = next;
        }

        public Node (E e){
            this(e,null);
        }

        public Node(){
            this(null,null);
        }
        @Override
        public String toString(){
            return e.toString();
        }
    }


    /**
     * 入队
     * @param e
     */
    public void enqueue(E e) {
        if (tail==null){
            tail=new Node(e);
            head = tail;
        }else{
            tail.next = new Node(e);
            tail = tail.next;
        }
        size++;



    }

    /**
     * 出队
     * @return
     */
    public E dequeue() {
        if (isEmpty()){
            throw new IllegalArgumentException("Cannot dequeue  from  an empty  queue");
        }
        Node retNode = head;
        head = head.next;
        retNode.next = null;
        if (head==null){
            tail=null;
        }
        size--;
        return retNode.e;
    }

    public E getFront() {
        return  head.e;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public String toString() {
        // TODO: 2018/5/3
        StringBuilder res = new StringBuilder();
        res.append("head:[");
        Node retNode = head;

        for (int i=0;i<getSize();i++){
            res.append(retNode.e+",");
            retNode=retNode.next;
        }
        res.append("]tail");
        return res.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> listQueue = new LinkedListQueue<Integer>();
        for (int i=0;i<10;i++){
            listQueue.enqueue(i);
            System.out.println(listQueue);
        }
        listQueue.dequeue();
        System.out.println(listQueue);


    }
}
